<template>
	<view class="page">
		<!-- 物流信息卡 -->
		<view class="card">
			<view class="card-title">物流信息</view>
			<view class="row">
				<text class="label">发货模式</text>
				<view class="seg">
					<view class="seg-item" :class="{ active: form.shippingType === '1' }" @click="form.shippingType = '1'">系统发货</view>
					<view class="seg-item" :class="{ active: form.shippingType === '2' }" @click="form.shippingType = '2'">自主发货</view>
				</view>
			</view>
			<view class="row">
				<text class="label">物流公司</text>
				<picker v-if="form.shippingType === '1'" :range="companyLabels" @change="onPickCompany" range-key="label">
					<view class="select-box">{{ currentCompanyLabel || '请选择物流公司' }}</view>
				</picker>
				<picker v-if="form.shippingType === '2'" :range="companyLabels" @change="onPickCompany" range-key="label">
					<view class="select-box">{{ currentCompanyLabel || '请选择物流公司' }}</view>
				</picker>
			</view>

			<view v-if="form.shippingType === '2'" class="row">
				<text class="label">物流单号</text>
				<input class="input" v-model="form.logisticsNo" maxlength="20" placeholder="输入物流单号" />
			</view>
		</view>

		<!-- 订单信息卡 -->
		<view class="card">
			<view class="card-title">订单信息</view>

			<view class="meta">
				<view class="meta-row">
					<text class="k">订单号：</text>
					<text class="v">{{ order.orderNo || '--' }}</text>
				</view>
				<view class="meta-row">
					<text class="k">收件人：</text>
					<text class="v">{{ order.receiverName }} {{ order.receiverPhone }}</text>
				</view>
				<view class="meta-row">
					<text class="k">下单时间：</text>
					<text class="v">{{ order.orderTime || '--' }}</text>
				</view>
				<view class="meta-row">
					<text class="k">金额：</text>
					<text class="v">¥{{ (order.orderPrice ?? 0).toFixed(2) }}</text>
				</view>
				<view class="meta-row">
					<text class="k">收货地址：</text>
					<text class="v address">{{ order.receiverAddress }}</text>
				</view>
			</view>
		</view>

		<!-- 备注编辑卡 -->
		<view class="card">
			<view class="card-title">打印备注</view>

			<view class="remark-row">
				<text class="edit-icon">✎</text>
				<textarea class="remark-box" v-model="form.remark" placeholder="打印备注：业务员自定义模板-实付金额-商品数量，可编辑" auto-height />
			</view>

			<view class="hint">提示：备注会随打印/发货记录保存，可手动编辑。</view>
		</view>

		<!-- 底部固定操作栏 -->
		<view class="bottom-bar">
			<button class="btn ghost" @click="onCancel">取消</button>
			<button v-if="form.shippingType === '1'" class="btn primary" @click="onSubmit">确认打印</button>
			<button v-else class="btn success" @click="onSubmit">确认发货</button>
		</view>
	</view>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted, watch, computed } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { logisticsShipping } from '@/api/order/list.js';
import { useUserStore } from '../../store';
import { useDict } from '../../utils/dict';
import { getRepeatPurchaseOrder } from '../../api/platformOrders/orders/repeatPurchaseOrder';
import { navBack, setLoadingToast, setToast } from '../../common/utils';
import { useLogisticsAction } from '@/hooks/useLogisticsAction';
// -- state
const user: any = useUserStore();

const order = reactive<any>({
	orderId: '',
	orderNo: '',
	receiverName: '',
	receiverPhone: '',
	receiverAddress: '',
	orderTime: '',
	orderPrice: 0,
	actualPrice: 0,
	productCollection: []
});

const form = reactive({
	shippingType: '1' as '1' | '2',
	logisticsPlatformCode: '',
	logisticsNo: '',
	remark: ''
});

// 字典集合
const {
	sys_logistics_company: logisticsCompany, // 物流公司
	sys_pay_type: payType, // 支付类型
	sys_replenish_order: replenishTypeOptions, // 订单类型
	sys_order_from: orderFrom, // 订单来源
	sys_self_fulfillment_ogistics: sysSelfFulfillmentOgistics, // 第三方快递
	sys_logistics_type: logisticsTypeOptions // 物流类型
}: any = useDict(
	'sys_logistics_company',
	'sys_pay_type',
	'sys_goods_type',
	'sys_order_type',
	'sys_replenish_order',
	'sys_sales_return',
	'sys_order_from',
	'sys_self_fulfillment_ogistics',
	'sys_logistics_type'
);

// 使用 Hook，传入刷新方法
const { execute } = useLogisticsAction(onCancel);

const currentCompanyLabel = ref('');

const companyLabels = computed(() => {
	return form.shippingType === '1' ? logisticsCompany.value : sysSelfFulfillmentOgistics.value;
});

// -- helpers
function onPickCompany(e: any) {
	const idx = Number(e.detail.value);
	const item = companyLabels.value[idx];
	form.logisticsPlatformCode = item?.value || '';
	currentCompanyLabel.value = item?.label || '';
}

// 自动拼备注：user.printStr + 实付金额 + 商品数量（与 PC 保持一致）
function autoBuildRemark() {
	if (!order || !order.productCollection) return;
	let shopStr = (user.printStr || '') + '-';
	shopStr += `实付金额：${(order.actualPrice ?? order.orderPrice ?? 0).toFixed(2)}元 - `;
	order.productCollection.forEach((item: any) => {
		if (!item.num) return;
		shopStr += `商品${item.productName}*${item.num}件 - `;
	});
	form.remark = shopStr.replace(/ - $/, '');
}

// 校验
function validate() {
	if (!form.logisticsPlatformCode) {
		uni.showToast({ title: '请选择物流公司', icon: 'none' });
		return false;
	}
	if (form.shippingType === '2' && !form.logisticsNo) {
		uni.showToast({ title: '请输入物流单号', icon: 'none' });
		return false;
	}
	return true;
}

// 提交
async function onSubmit() {
	if (!validate()) return;
	setLoadingToast('正在提交中....');
	const args = {
		orderId: order.orderId,
		remark: form.remark,
		shippingType: form.shippingType,
		logisticsNo: form.logisticsNo,
		logisticsPlatformCode: form.logisticsPlatformCode
	};
	try {
		const res: any = await logisticsShipping(args);
		uni.hideLoading();
		// 你可以根据后端返回结构调整判定
		if (res && res.code === 200) {
			setToast('发货成功');
			navBack();
			// 返回上一页并可刷新列表（上页监听 onShow 或接收回调）
		} else {
			setToast(res?.msg || '操作失败');
		}
	} catch (err: any) {
		setToast(err?.message || '网络错误');
	}
}

function onCancel() {
	// 直接返回
	navBack();
}

// 当 user.printStr 或 order 变化时重新拼备注（保持与 PC 逻辑一致）
watch(
	() => [user.printStr, order.productCollection, order.actualPrice],
	() => {
		autoBuildRemark();
	},
	{ deep: true }
);

const getData = (id) => {
	getRepeatPurchaseOrder(id).then((res) => {
		Object.assign(order, res.data);
		// 生成备注
		autoBuildRemark();
	});
};

// 页面初始化：尝试从路由拿 orderId 并拉取详情（若无则使用传入的 order 数据或 Mock）
onLoad(async (options) => {
	getData(options.id);
});
</script>

<style scoped lang="scss">
.page {
	min-height: 100vh;
	padding: 24rpx;
	background: #f6f8fb;
	padding-bottom: 160rpx; /* 为底部按钮留空间 */
}
.top-bar {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 18rpx;
}
.title {
	font-size: 34rpx;
	font-weight: 700;
	color: #111827;
}
.sub {
	font-size: 24rpx;
	color: #6b7280;
}

.card {
	background: #fff;
	border-radius: 18rpx;
	padding: 24rpx;
	margin-bottom: 18rpx;
	box-shadow: 0 8rpx 20rpx rgba(2, 6, 23, 0.04);
}
.card-title {
	font-size: 28rpx;
	font-weight: 600;
	color: #111827;
	margin-bottom: 12rpx;
}

.row {
	display: flex;
	align-items: center;
	margin-top: 12rpx;
}
.label {
	width: 160rpx;
	color: #6b7280;
}
.select-box {
	height: 72rpx;
	line-height: 72rpx;
	padding: 0 20rpx;
	background: #f9fafb;
	border-radius: 12rpx;
	color: #374151;
}
.input {
	height: 72rpx;
	padding: 0 20rpx;
	background: #f9fafb;
	border-radius: 12rpx;
	flex: 1;
	color: #111827;
}

.seg {
	display: flex;
	width: 420rpx;
	background: #f3f4f6;
	border-radius: 12rpx;
	padding: 6rpx;
	gap: 8rpx;
}
.seg-item {
	flex: 1;
	text-align: center;
	padding: 16rpx 0;
	border-radius: 10rpx;
	color: #374151;
}
.seg-item.active {
	background: #2563eb;
	color: #fff;
}

.meta {
	margin-top: 8rpx;
	color: #374151;
}
.meta-row {
	display: flex;
	margin: 8rpx 0;
	// border: 1px solid red;
	align-items: center;
}
.k {
	width: 150rpx;
	color: #6b7280;
}
.v {
	color: #111827;
	flex: 1;
}
.address {
	overflow: hidden;
	white-space: nowrap;
	text-overflow: ellipsis;
}

.remark-row {
	display: flex;
	gap: 12rpx;
	align-items: flex-start;
}
.edit-icon {
	font-size: 26rpx;
	color: #2563eb;
	margin-top: 8rpx;
}
.remark-box {
	flex: 1;
	min-height: 140rpx;
	padding: 16rpx;
	border-radius: 12rpx;
	background: #f9fafb;
	color: #111827;
	font-size: 28rpx;
}
.hint {
	margin-top: 12rpx;
	color: #9ca3af;
	font-size: 24rpx;
}

.bottom-bar {
	position: fixed;
	left: 0;
	right: 0;
	bottom: 0;
	padding: 20rpx;
	display: flex;
	gap: 16rpx;
	background: rgba(255, 255, 255, 0.9);
	box-shadow: 0 -8rpx 20rpx rgba(2, 6, 23, 0.04);
}
.btn {
	flex: 1;
	height: 84rpx;
	border-radius: 14rpx;
	font-weight: 700;
	border: none;
}
.btn.ghost {
	background: #fff;
	border: 2rpx solid #e6e9ef;
	color: #374151;
}
.btn.primary {
	background: #2563eb;
	color: #fff;
}
.btn.success {
	background: #16a34a;
	color: #fff;
}
</style>
